from system.fsm import Fsm
from system.eventServer import eventServer
from system.dynload import dynload

class Controller(Fsm):
    def __init__(self, parent, type = None, name = None):
        Fsm.__init__(self, parent, ['update'], type, name)
        
        self.sensors = {}
        self.actuators = {}
        
        self.sensorOffset = 0
        self.actuatorOffset = 0
        
    def addSensor(self, type, name = None, vars = None):
        if not name:
            name = self.makeName(type,self.sensors.keys())
        if not vars:
            vars = {}
            
        sensorClass = dynload(type)
        assert sensorClass, "unable to load sensor class %s" % type
        sensor = sensorClass(self,vars)
        self.sensors[name] = sensor
        
        sensor.bitOffset = self.sensorOffset
        self.sensorOffset += sensor.numBits
        
        return sensor
            
    def addActuator(self, type, name = None, vars = None):
        if not name:
            name = self.makeName(type,self.actuators.keys())
        if not vars:
            vars = {}
            
        actuatorClass = dynload(type)
        assert actuatorClass, "unable to load actuator class %s" % type
        actuator = actuatorClass(self,vars)
        self.actuators[name] = actuator
        
        actuator.bitOffset = self.actuatorOffset
        self.actuatorOffset += actuator.numBits
        
        return actuator
        
    def clearSensors(self):
        self.sensors = {}
        self.sensorOffset = 0
        
    def clearActuators(self):
        self.actuators = {}
        self.actuatorOffset = 0
        
    def makeName(self, base, names):
        if not base in names:
            return base
        i = 2
        name = "%s_%d" % (base,i)
        while name in names:
            i += 1
            name = "%s_%d" % (base,i)
        return name
